﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AK.FTP
{
    public partial class FrmFtp : Form
    {
        private Shell32.Folder m_RootShell;
        private Shell32.Folder m_currentFolder;
        private Icon m_IconFolder;
        private Shell32.Shell m_Shell;

        public FrmFtp()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;

            m_Shell = new Shell32.ShellClass();
            m_RootShell = m_Shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfDRIVES);

            InitializeIconFolder();
            FillLocalView(m_RootShell);
        }

        #region FTP绑定事件

        private void ftpc_Connected(object sender, Core.FTPEventArgs e)
        {
            //连接成功后登陆
            ftpc.Login();
        }

        private void ftpc_ConnectionFailure(object sender, Core.FTPEventArgs e)
        {

        }

        private void ftpc_ConnectionTerminated(object sender, Core.FTPEventArgs e)
        {

        }

        private void ftpc_DirCompleted(object sender, Core.FTPEventArgs e)
        {
            int i = 0;
            int idimage = 0;
            string msg;

            msg = "Transfered " + e.TotalBytes.ToString() + " bytes in " + ((float)e.TimeElapsed / 1000).ToString() + " seconds";
            DisplayLog(msg);

            lstServer.BeginUpdate();
            lstServer.Items.Clear();
            ImgListServerSmall.Images.Clear();

            ListViewItem lvItem = new ListViewItem("..");
            lstServer.Items.Add(lvItem);

            for (i = 0; i < ftpc.FileCount; i++)
            {
                if (ftpc.IsFolder(i))
                {
                    string[] items = new String[2];
                    items[0] = ftpc.GetFileName(i);
                    items[1] = ftpc.GetFileSize(i).ToString();
                    if (items[0] == "." || items[0] == "..")
                        continue;
                    ImgListServerSmall.Images.Add(m_IconFolder);
                    lstServer.Items.Add(new ListViewItem(items, idimage++));
                }
            }
            for (i = 0; i < ftpc.FileCount; i++)
            {
                if (!ftpc.IsFolder(i))
                {
                    string[] items = new String[2];
                    items[0] = ftpc.GetFileName(i);
                    items[1] = ftpc.GetFileSize(i).ToString();
                    ImgListServerSmall.Images.Add(ExtractIcon.GetIcon(items[0], false));
                    lstServer.Items.Add(new ListViewItem(items, idimage++));
                }
            }
            lstServer.EndUpdate();
            this.Cursor = Cursors.Default;
        }

        private void ftpc_FileUploadCompleted(object sender, Core.FTPEventArgs e)
        {

        }

        private void ftpc_Error(object sender, Core.FTPEventArgs e)
        {
            DisplayLog(e.Message,MessageTypeEnum.Error);
        }

        private void ftpc_Logged(object sender, Core.FTPEventArgs e)
        {
            ftpc.Dir();
        }

        private void ftpc_FileDownloadCompleted(object sender, Core.FTPEventArgs e)
        {
            MessageBox.Show("Download completed");
        }

        private void ftpc_FTPCommand(object sender, Core.FTPEventArgs e)
        {
            DisplayLog(e.Message);
        }

        private void ftpc_Message(object sender, Core.FTPEventArgs e)
        {
            DisplayLog("[Message]" + e.Message);
        }
        #endregion

        private void btnConnect_ButtonClick(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cboServerUrl.Text) ||
                string.IsNullOrEmpty(txtUserName.Text) ||
                string.IsNullOrEmpty(txtPassword.Text) ||
                string.IsNullOrEmpty(txtPort.Text))
            {
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            try
            {
                DisplayLog(string.Format("正在连接 [{0}]", cboServerUrl.Text));
                this.Connect();
                DisplayLog(string.Format("连接成功[{0}]", cboServerUrl.Text));
                
                btnDisconnect.Enabled = true;
                btnSync.Enabled = true;
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Default;
                DisplayLog(ex.Message, MessageTypeEnum.Error);
                return;
            }

            this.Cursor = Cursors.Default;
        }

        //连接
        private void Connect()
        {
            this.Cursor = Cursors.WaitCursor;

            ftpc.Username = txtUserName.Text;
            ftpc.Password = txtPassword.Text;

            ftpc.Hostname = cboServerUrl.Text;
            ftpc.Connect();

            
            
        }

        private void FillLocalView(Shell32.Folder folder)
        {

            this.Cursor = Cursors.WaitCursor;

            m_currentFolder = folder;
            // Notify that update begins
            lstLocal.BeginUpdate();

            // Erase last view items
            lstLocal.Items.Clear();

            // Erase previous lists image
            ImgListViewSmall.Images.Clear();
            ImgListViewLarge.Images.Clear();

            int idImage = 0;

            ListViewItem lvItem = new ListViewItem("..");
            lvItem.Tag = folder;

            lstLocal.Items.Add(lvItem);

            Shell32.FolderItems items = folder.Items();

            // Folder enumeration
            foreach (Shell32.FolderItem item in items)
            {
                if (item.IsFolder)
                {
                    AddViewItem(item, ref idImage);
                }
            }

            // Other files 
            foreach (Shell32.FolderItem item in items)
            {
                if (!item.IsFolder)
                {
                    AddViewItem(item, ref idImage);
                }
            }

            // End update view
            lstLocal.EndUpdate();

            //ftpc.LocalFolder = folder.Title;

            this.Cursor = Cursors.Default;

        }

        private void AddViewItem(Shell32.FolderItem item, ref int idImage)
        {
            string[] sValues = new string[10];

            sValues[0] = item.Name;
            if (item.Size == 0)
                sValues[1] = "";
            else
                sValues[1] = Convert.ToString(item.Size / 1024) + " KB";
            sValues[2] = item.Type;
            sValues[3] = item.ModifyDate.ToString();
            /*
            sValues[4] = item.Path;
            sValues[5] = item.IsBrowsable.ToString();
            sValues[6] = item.IsFileSystem.ToString();
            sValues[7] = item.IsFolder.ToString();
            sValues[8] = item.IsLink.ToString();
            */
            ImgListViewSmall.Images.Add(ExtractIcon.GetIcon(item.Path, true));

            ListViewItem lvItem = new ListViewItem(sValues, idImage++);
            lvItem.Tag = item;
            lstLocal.Items.Add(lvItem);
        }

        private void InitializeIconFolder()
        {
            Shell32.Folder FolderShell = m_Shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfWINDOWS);
            Shell32.FolderItems items = FolderShell.Items();

            foreach (Shell32.FolderItem item in items)
                if (item.IsFolder)
                {
                    m_IconFolder = ExtractIcon.GetIcon(item.Path, true);
                    break;
                }
        }

        private void Download()
        {
            for (int i = 0; i < lstServer.SelectedItems.Count; i++)
            {
                ftpc.FileDownload(lstServer.SelectedItems[i].Text);
            }
        }

        //显示日志记录
        private void DisplayLog(string msg, MessageTypeEnum type)
        {
            msg = string.Format("[{0}]{1}", DateTime.Now, msg);
            if (string.IsNullOrEmpty(msg))
                return;

            if (txtLog.Text.Length == 0)
            {
                txtLog.Text = msg;
            }
            else
            {
                txtLog.Text += "\r\n" + msg;
            }

            txtLog.SelectionStart = 0;
            txtLog.SelectionLength = msg.Length - 1;
            txtLog.SelectionColor = type == MessageTypeEnum.Error ? Color.Red : Color.DodgerBlue;
            txtLog.ScrollToCaret();
        }

        private void DisplayLog(string msg)
        {
            DisplayLog(msg, MessageTypeEnum.Normal);
        }

        //点击获取文件列表
        private void lstServer_ItemActivate(object sender, EventArgs e)
        {
            if (lstServer.SelectedItems[0].Text == "..")
            {
                this.Cursor = Cursors.WaitCursor;
                ftpc.DirUp();
                ftpc.Dir();
            }
            else
            {
                string dirname = lstServer.SelectedItems[0].Text;
                if (ftpc.IsFolder(dirname))
                {
                    this.Cursor = Cursors.WaitCursor;

                    ftpc.DirChange(dirname);
                    ftpc.Dir();
                }
            }
        }

        private void lstLocal_ItemActivate(object sender, EventArgs e)
        {
            if (lstLocal.SelectedItems[0].Text == "..")
            {
                Shell32.Folder item;

                item = (Shell32.Folder)lstLocal.SelectedItems[0].Tag;
                FillLocalView((Shell32.Folder)item.ParentFolder);
            }
            else
            {
                Shell32.FolderItem item;

                item = (Shell32.FolderItem)lstLocal.SelectedItems[0].Tag;
                if (item.IsFolder)
                {
                    ftpc.LocalFolder = item.Path;
                    FillLocalView((Shell32.Folder)item.GetFolder);
                }
            }
        }

        //下载事件
        private void download_DToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Download();
        }
    }
}
